const mosca = require("mosca");
const MqttServer = new mosca.Server({
  port: 1883,
  //设置websocket：https://www.cnblogs.com/Joans/p/9957128.html
  http:{
    port:1884,
    static:'./'
  }
});
MqttServer.on("clientConnected", function (client) {
  //当有客户端连接时的回调.
  console.log("client connected", client.id);
});
/**
 * 监听MQTT主题消息
 * 当客户端有连接发布主题消息时
 **/
MqttServer.on("published", function (packet, client) {
  var topic = packet.topic;
  console.log(topic)
  switch (topic) {
    case "temperature":
      // console.log('message-publish', packet.payload.toString());
      //MQTT可以转发主题消息至其他主题
      MqttServer.publish({
        topic: 'other',
        payload: 'sssss'
      });
      break;
    case "other":
      console.log("message-123", packet.payload.toString());
      break;
    case "RequestConfigInit":
      // console.log('message-publish', packet.payload.toString());
      //MQTT可以转发主题消息至其他主题
      MqttServer.publish({
        topic: 'ConfigInitFromEdge',
        payload: JSON.stringify({0:{code_name:'unknown',name:'-',offset:4,},1:{code_name:'error',name:'-',offset:4,},2:{code_name:'Brain',name:'头部',offset:6,},3:{code_name:'Thorax',name:'胸部',offset:7,},4:{code_name:'Abdomen',name:'腹部',offset:8,},5:{code_name:'ThoraxAbdomen',name:'胸腹',offset:7,},6:{code_name:'unknown',name:'-',offset:4,},7:{code_name:'Pelvis',name:'盆腔',offset:4,},8:{code_name:'C_Spine',name:'颈椎',offset:4,},9:{code_name:'T_Spine',name:'胸椎',offset:4,},10:{code_name:'L_Spine',name:'腰椎',offset:4}})
      });
      break;
  }
});

MqttServer.on("ready", function () {
  //当服务开启时的回调
  console.log("mqtt is running...");
});
